using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.UserControls;
using Telerik.Web.UI;

namespace Code5Systems.FormMaster
{
	
	public partial class FormReport : DotNetNuke.Entities.Modules.PortalModuleBase
	{

#region Private Members

		private HtmlInputHidden _hdnWzrdStart;
		private HtmlGenericControl _head;
		private bool _isMultiPage = false;
		private bool _hasFileUploadControls = false;
		private XDocument _xDoc;
		private DotNetNuke.Entities.Modules.PortalModuleBase _loaderCtl;
		private Code5Systems.FormMaster.Business.FormInfo _objFormInfo;
		private string _validationGroup;
		private Code5Systems.FormMaster.Business.FormController _objFormCtl;
		private FormSettings _objFormSettings;
		private int _intFormDataId = -1;
		private int _fdid = 0;
		private List<string> _disabledValidators = new List<string>();
		private bool _singleRecordMode = false;
#endregion

#region  Web Form Designer Generated Code

		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		protected System.Web.UI.WebControls.LinkButton cmdView;
		protected System.Web.UI.WebControls.LinkButton cmdExcel;
		protected LinkButton cmdExcel2007;
		protected System.Web.UI.WebControls.LinkButton cmdDelete;
		protected System.Web.UI.WebControls.LinkButton cmdCsv;
		protected System.Web.UI.WebControls.HyperLink cmdStartCalendar;
		protected System.Web.UI.WebControls.HyperLink cmdEndCalendar;
		protected Telerik.Web.UI.RadDatePicker txtStartDate;
		protected RadGrid dgFormReport;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvStartDate;
		protected System.Web.UI.WebControls.CompareValidator cvStartDate;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvEndDate;
		protected System.Web.UI.WebControls.CompareValidator cvEndDate;
		protected Telerik.Web.UI.RadDatePicker txtEndDate;
		protected DotNetNuke.UI.UserControls.LabelControl lblStartCalendar;
		protected DotNetNuke.UI.UserControls.LabelControl lblEndCalendar;
		protected System.Web.UI.WebControls.Panel pnlReport;
		protected System.Web.UI.WebControls.Label lblHeading;
		protected System.Web.UI.WebControls.Panel phForm;
		protected System.Web.UI.WebControls.LinkButton cmdSubmit;
		protected System.Web.UI.WebControls.Panel pnlForm;
		protected System.Web.UI.HtmlControls.HtmlTable tblForm;
		protected System.Web.UI.WebControls.LinkButton cmdCancel;
		protected System.Web.UI.WebControls.Label lblDownload;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
			Response.Buffer = true;
			
			//Get the Module Settings
			_objFormSettings = Utility.GetFormSettings(ModuleId);
			
			_objFormCtl = new Code5Systems.FormMaster.Business.FormController(ModuleId);
			
			//Get the FormInfo Object
			_objFormInfo = _objFormCtl.FormInfo;
			
			CreateForm();
		}
		
#endregion

#region Create Form

		private void CreateForm()
		{
			_head = this.Page.FindControl("Head") as HtmlGenericControl;

			_hdnWzrdStart = this.pnlForm.FindControl("hdnWzrdStart") as HtmlInputHidden;
			if (_hdnWzrdStart == null)
			{
				_hdnWzrdStart = new HtmlInputHidden() { ID = "hdnWzrdStart", Value = "0" };
				_hdnWzrdStart.Attributes.Add("class", String.Format("C5S_wzrdstart_{0}", this._objFormInfo.FormID));
				this.phForm.Controls.Add(_hdnWzrdStart);
			}

			if (_objFormCtl.Pages.Count == 1)
			{
				//_objFormCtl.CreateForm(ModuleId, this.phForm, false);

				if (_objFormSettings.ResponsiveLayout)
				{
					this._objFormCtl.CreateFormRwd(ModuleId, this.phForm, false);
				}
				else
				{
					this._objFormCtl.CreateForm(ModuleId, this.phForm, false);
				}

				this.formWizard.Visible = false;
				this.phForm.Visible = true;
				this.cmdSubmit.Visible = true;

				// Remove any custom Buttons
				foreach (Button btn in Utility.GetChildsRecursive(this.phForm).OfType<Button>())
				{
					btn.Visible = false;
				}

				// Remove any custom LinkButtons
				foreach (LinkButton btn in Utility.GetChildsRecursive(this.phForm).OfType<LinkButton>())
				{
					btn.Visible = false;
				}

				// Remove any custom ImageButtons
				foreach (ImageButton btn in Utility.GetChildsRecursive(this.phForm).OfType<ImageButton>())
				{
					btn.Visible = false;
				}

				//_validationGroup = _objFormCtl.ValidationGroup;

			}
			else
			{

				HtmlGenericControl wzrdScriptTag;
#if DEBUG
				if (_head != null && _head.FindControl("C5SLLC_wizard") == null)
				{
					wzrdScriptTag = new HtmlGenericControl("script");
					wzrdScriptTag.ID = "C5SLLC_wizard";
					wzrdScriptTag.Attributes.Add("type", "text/javascript");
					wzrdScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-formToWizard.js", Utility.GetAppPath()));
					_head.Controls.Add(wzrdScriptTag);
				}
#else

				if (_head != null && _head.FindControl("C5SLLC_wizard") == null)
				{
					wzrdScriptTag = new HtmlGenericControl("script");
					wzrdScriptTag.ID = "C5SLLC_wizard";
					wzrdScriptTag.Attributes.Add("type", "text/javascript");
					wzrdScriptTag.Attributes.Add("src", String.Format("{0}DesktopModules/Code5Systems_FormMaster/assets/js/jquery-formToWizard.min.js", Utility.GetAppPath()));
					_head.Controls.Add(wzrdScriptTag);
				}
#endif
				_validationGroup = _objFormCtl.FormInfo.ValidationGroup;
				_isMultiPage = true;
				this.phForm.CssClass = String.Format("C5SLLC_wizard_{0}", this._objFormInfo.FormID);

				if (!String.IsNullOrWhiteSpace(_objFormSettings.TableWidth))
				{
					phForm.Width = Unit.Parse(_objFormSettings.TableWidth);
				}

				switch (_objFormSettings.TableAlignment)
				{
					case HorizontalAlign.Left:
						this.phForm.CssClass += " C5SLLC_left";
						break;
					case HorizontalAlign.Center:
						this.phForm.CssClass += " C5SLLC_center";
						break;
					case HorizontalAlign.Right:
						this.phForm.CssClass += " C5SLLC_right";
						break;
				}

				foreach (Code5Systems.FormMaster.Business.FormPageInfo oPage in _objFormCtl.Pages)
				{
					_objFormCtl.FormInfo.CurrentPage = oPage;
					if (!_hasFileUploadControls)
					{
						this._xDoc = XDocument.Parse(oPage.PageData);
						_hasFileUploadControls = (from s in this._xDoc.Root.Elements("Controls").Elements("Control")
												  where s.Attributes("Type").First().Value == "FileUpload"
												  orderby s.Attributes("TableRow").First().Value
												  select s).Count() > 0;
					}

					HtmlGenericControl fieldSet = new HtmlGenericControl("fieldset");
					fieldSet.ID = String.Format("C5SLLC_Step{0}", oPage.PageNum);

					if (!String.IsNullOrWhiteSpace(_objFormSettings.FormTableWidth))
					{
						if (_objFormSettings.FormTableWidth.EndsWith("%"))
						{
							fieldSet.Attributes.Add("style", String.Format("width:{0};", _objFormSettings.FormTableWidth));
						}
						else
						{
							fieldSet.Attributes.Add("style", String.Format("width:{0}px;", _objFormSettings.FormTableWidth));
						}

					}

					HtmlGenericControl legend = new HtmlGenericControl("legend");
					legend.InnerText = oPage.ShortName;
					switch (_objFormSettings.WizardLegendAlign)
					{
						case HorizontalAlign.Left:
							legend.Attributes.Add("class", String.Format("textleft {0}", _objFormSettings.WizardLegendClass));
							break;
						case HorizontalAlign.Center:
							legend.Attributes.Add("class", String.Format("textcenter {0}", _objFormSettings.WizardLegendClass));
							break;
						case HorizontalAlign.Right:
							legend.Attributes.Add("class", String.Format("textright {0}", _objFormSettings.WizardLegendClass));
							break;
						default:
							legend.Attributes.Add("class", _objFormSettings.WizardStepClass);
							break;
					}

					fieldSet.Controls.Add(legend);

					if (_objFormCtl.FormInfo.CurrentPage.UseTitle)
					{
						string titleClass = String.Format("frmwizardheader {0}", _objFormSettings.WizardStepTitleClass);
						string titleStyle = String.Empty;
						HtmlGenericControl pageTitle = new HtmlGenericControl("div");
						pageTitle.InnerHtml = oPage.Title;

						switch (_objFormSettings.WizardTitleAlign)
						{
							case HorizontalAlign.Left:
								titleClass += " textleft";
								break;
							case HorizontalAlign.Center:
								titleClass += " textcenter";
								break;
							case HorizontalAlign.Right:
								titleClass += " textright";
								break;
						}

						pageTitle.Attributes.Add("class", titleClass);
						fieldSet.Controls.Add(pageTitle);
					}



					this.phForm.Controls.Add(fieldSet);

					if (_objFormSettings.ResponsiveLayout)
					{
						this._objFormCtl.CreateFormRwd(ModuleId, fieldSet, false);
					}
					else
					{
						this._objFormCtl.CreateForm(ModuleId, fieldSet, false);
					}

					this._objFormCtl.SetWizardCallScripts(this.pnlDynScripts);
				}

				if (_objFormSettings.ResponsiveLayout)
				{
					if (!String.IsNullOrWhiteSpace(_objFormSettings.TableWidth))
					{
						if (_objFormSettings.TableWidth.Contains("%"))
						{
							double width;
							if (double.TryParse(_objFormSettings.TableWidth, out width))
							{
								this.pnlForm.Width = Unit.Percentage(width);
							}
						}
						else
						{
							int width;
							if (int.TryParse(_objFormSettings.TableWidth, out width))
							{
								this.pnlForm.Width = Unit.Pixel(width);
							}
						}

						this.pnlForm.CssClass = "C5SLLC_width";
					}

					if (_objFormSettings.TableAlignment != HorizontalAlign.NotSet)
					{
						switch (_objFormSettings.TableAlignment)
						{
							case HorizontalAlign.Center:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_center";
								break;
							case HorizontalAlign.Left:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_left";
								break;
							case HorizontalAlign.Right:
								this.pnlForm.CssClass = "C5SLLC_width C5SLLC_right";
								break;
						}
					}
				}
			}
		}
		
#endregion

#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			try
			{
				this.LoaderCtl = (PortalModuleBase) this.Parent.Parent;
				
				if (!(ViewState["FormDataID"] == null))
				{
					_intFormDataId = System.Convert.ToInt32(ViewState["FormDataID"]);
				}

				//'Get the Module Settings
				//objFormSettings = Utility.GetFormSettings(ModuleId)
				
				//objFormCtl = New FormController(ModuleId)
				
				//'Get the FormInfo Object
				//objFormInfo = objFormCtl.FormInfo
				
				//Localization.LocalizeDataGrid(ref dgFormReport, LocalResourceFile);
				
				if (!this.Page.IsPostBack)
				{
					if (DotNetNuke.Framework.AJAX.IsInstalled())
					{
						DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdSubmit);
					}

					this.dgFormReport.AutoGenerateColumns = true;
					this.dgFormReport.AllowPaging = true;
					this.dgFormReport.AllowCustomPaging = true;
					this.dgFormReport.AllowSorting = true;
					this.dgFormReport.MasterTableView.AllowNaturalSort = false;
					this.cmdExcel.ToolTip = Localization.GetString("cmdExcelToolTip", LocalResourceFile);
					this.cmdExcel2007.ToolTip = Localization.GetString("cmdExcel2007ToolTip", LocalResourceFile);
					this.cmdWord.ToolTip = Localization.GetString("cmdWordToolTip", LocalResourceFile);
					this.cmdPDF.ToolTip = Localization.GetString("cmdPDFToolTip", LocalResourceFile);
					this.cmdCsv.ToolTip = Localization.GetString("cmdCsvToolTip", LocalResourceFile);
					this.cmdTab.ToolTip = Localization.GetString("cmdTabToolTip", LocalResourceFile);
					this.cmdView.ToolTip = Localization.GetString("cmdViewToolTip", LocalResourceFile);
					this.cmdDelete.ToolTip = Localization.GetString("cmdDeleteToolTip", LocalResourceFile);
					SetReportButtons(false);
					LocalizeGrid();
				}
				
				if (!Page.IsPostBack)
				{
					this.pnlReport.Visible = true;
					this.pnlForm.Visible = false;
					
					CultureInfo userCulture = Utility.GetUserCulture();
					
					this.txtStartDate.SelectedDate = DateTime.Now.AddDays(-30);
					this.txtEndDate.SelectedDate = DateTime.Now;
					
					if (userCulture.Name == "hu-HU" || userCulture.Name == "bg-BG")
					{
						this.cvStartDate.Enabled = false;
						this.cvEndDate.Enabled = false;
					}
				}
				
				if (DotNetNuke.Framework.AJAX.IsEnabled())
				{
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdCsv);
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdExcel);
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdExcel2007);
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdPDF);
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdTab);
					DotNetNuke.Framework.AJAX.RegisterPostBackControl(this.cmdWord);
				}

				this.lblSingleDataModeMsg.Visible = false;

				if (!String.IsNullOrWhiteSpace(Request.QueryString["fdid"]))
				{
					if (int.TryParse(Request.QueryString["fdid"], out _fdid))
					{
						if (_fdid > 0)
						{
							BindGrid();
							_singleRecordMode = true;
							this.lblSingleDataModeMsg.Visible = true;
							this.cmdView.Enabled = false;
							this.cmdDelete.Enabled = false;
						}
					}
				}
			}
			catch (Exception exc)
			{
				Exceptions.ProcessModuleLoadException(LoaderCtl, exc);
			}
		}

		bool IsTab = false;

		protected void dgFormReport_GridExporting(object source, GridExportingArgs e)
		{
			switch (e.ExportType)
			{
				case ExportType.Excel:
					//do something with the e.ExportOutput value      
					break;
				case ExportType.ExcelML:
					//do something with the e.ExportOutput value     
					break;
				case ExportType.Word:
					//do something with the e.ExportOutput value   
					break;
				case ExportType.Csv:
					//do something with the e.ExportOutput value    
					if (IsTab)
					{
						e.ExportOutput = e.ExportOutput.Replace("\"", "");
						IsTab = false;
					}
					break;
			}
		}

		protected void dgFormReport_PdfExporting(object source, GridPdfExportingArgs e)
		{
			
		}

		protected void cmdView_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.CurrentPageIndex = 0;
				BindGrid();
			}
		}
		
		//Download data in Excel 2002+ HTML format
		protected void cmdExcel_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.ExportOnlyData = true;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.ExportSettings.Excel.Format = GridExcelExportFormat.Html;
				this.dgFormReport.ExportSettings.Excel.FileExtension = "xls";
				this.dgFormReport.MasterTableView.ExportToExcel();
			}
		}
		
		//Download data in Excel 2003+ XML format
		protected void cmdExcel2003_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.ExportOnlyData = true;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.ExportSettings.Excel.Format = GridExcelExportFormat.ExcelML;
				this.dgFormReport.ExportSettings.Excel.FileExtension = "xlsx";
				this.dgFormReport.MasterTableView.ExportToExcel();
			}
		}
		
		//Download Comma Separated Values Format
		protected void cmdCsv_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.ExportOnlyData = true;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.ExportSettings.Csv.FileExtension = "csv";
				this.dgFormReport.MasterTableView.ExportToCSV();
			}
		}

		//Download PDF Format
		protected void cmdPDF_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.Pdf.PageWidth = Unit.Pixel(1056);
				this.dgFormReport.ExportSettings.Pdf.PageHeight = Unit.Pixel(816);
				this.dgFormReport.ExportSettings.Pdf.PageBottomMargin = Unit.Pixel(20);
				this.dgFormReport.ExportSettings.Pdf.PageLeftMargin = Unit.Pixel(20);
				this.dgFormReport.ExportSettings.Pdf.PageRightMargin = Unit.Pixel(20);
				this.dgFormReport.ExportSettings.Pdf.PageTopMargin = Unit.Pixel(20);
				this.dgFormReport.ExportSettings.ExportOnlyData = false;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.Pdf.Title = GetExportFileName();
				this.dgFormReport.ExportSettings.Pdf.PageTitle = GetExportFileName();
				this.dgFormReport.ExportSettings.Pdf.AllowAdd = true;
				this.dgFormReport.ExportSettings.Pdf.AllowCopy = true;
				this.dgFormReport.ExportSettings.Pdf.AllowModify = true;
				this.dgFormReport.ExportSettings.Pdf.AllowPrinting = true;
				this.dgFormReport.ExportSettings.Pdf.Author = String.Format("{0} {1}", this.UserInfo.FirstName, this.UserInfo.LastName);
				this.dgFormReport.ExportSettings.Pdf.Creator = String.Format("{0} {1}", this.UserInfo.FirstName, this.UserInfo.LastName);
				this.dgFormReport.ExportSettings.Pdf.FontType = Telerik.Web.Apoc.Render.Pdf.FontType.Link;
				this.dgFormReport.ExportSettings.Pdf.Producer = String.Format("{0} {1}", this.UserInfo.FirstName, this.UserInfo.LastName);
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.ExportSettings.Excel.FileExtension = "pdf";
				this.dgFormReport.MasterTableView.ExportToPdf();
			}
		}

		protected void cmdWord_Click(object sender, EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.MasterTableView.ExportToWord();
			}
		}

		//Download Tab Delimited Format
		protected void cmdTab_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				IsTab = true;
				this.dgFormReport.MasterTableView.GetColumn("DeleteColumn1").Visible = false;
				this.dgFormReport.MasterTableView.GetColumn("EditColumn1").Visible = false;
				this.dgFormReport.PageSize = this.dgFormReport.MasterTableView.VirtualItemCount;
				this.dgFormReport.ExportSettings.ExportOnlyData = true;
				this.dgFormReport.ExportSettings.IgnorePaging = true;
				this.dgFormReport.ExportSettings.OpenInNewWindow = true;
				this.dgFormReport.ExportSettings.FileName = GetExportFileName();
				this.dgFormReport.ExportSettings.Csv.FileExtension = "txt";
				this.dgFormReport.ExportSettings.Csv.ColumnDelimiter = GridCsvDelimiter.Tab;
				this.dgFormReport.ExportSettings.Csv.RowDelimiter = GridCsvDelimiter.NewLine;
				this.dgFormReport.MasterTableView.ExportToCSV();
			}
		}
		
		//Delete the Data for the Specified Date Range
		protected void cmdDelete_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				try
				{
					Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
					
					DateTime dtEnd = default(DateTime);
					dtEnd = this.txtEndDate.SelectedDate.Value;
					dtEnd = System.Convert.ToDateTime(dtEnd.Date.AddDays(1).AddSeconds(-1));

					objFormDataCtl.DeleteRange(_objFormInfo, ModuleId, this.txtStartDate.SelectedDate.Value, dtEnd, this.ControlPath);
					
					//Response.Redirect(Request.RawUrl)
					BindGrid();
					
				}
				catch (IOException ioEx)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, ioEx.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				}
				catch (System.Data.SqlClient.SqlException sqlEx)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, sqlEx.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					
				}
				catch (Exception exc)
				{
					Exceptions.ProcessModuleLoadException(LoaderCtl, exc);
				}
			}
		}

		protected void dgFormReport_ItemDataBound(object sender, GridItemEventArgs e)
		{
			LinkButton lnkBtn = default(LinkButton);
			var lnkButtons = Utility.GetChildsRecursive(e.Item).OfType<LinkButton>();
			
			lnkBtn = lnkButtons.Where(b => b.Text == "Edit").SingleOrDefault();
			if (lnkBtn != null)
			{
				lnkBtn.Text = Localization.GetString("Edit.Grid", LocalResourceFile);
			}

			lnkBtn = lnkButtons.Where(b => b.Text == "Delete").SingleOrDefault();
			if (lnkBtn != null)
			{
				lnkBtn.CausesValidation = true;
				lnkBtn.Text = Localization.GetString("Delete.Grid", LocalResourceFile);
				lnkBtn.Attributes.Add("onclick", "javascript:return confirm(\'" + Localization.GetString("DeleteDataMessage", LocalResourceFile) + "\');");
			}

			Button button = default(Button);
			var buttons = Utility.GetChildsRecursive(e.Item).OfType<Button>();

			button = buttons.Where(b => b.ToolTip == "First Page").SingleOrDefault();
			if (button != null)
			{
				button.ToolTip = Localization.GetString("FirstPageText.Grid", LocalResourceFile);
			}

			button = buttons.Where(b => b.ToolTip == "Previous Page").SingleOrDefault();
			if (button != null)
			{
				button.ToolTip = Localization.GetString("PrevPageText.Grid", LocalResourceFile);
			}

			button = buttons.Where(b => b.ToolTip == "Next Page").SingleOrDefault();
			if (button != null)
			{
				button.ToolTip = Localization.GetString("NextPageText.Grid", LocalResourceFile);
			}

			button = buttons.Where(b => b.ToolTip == "Last Page").SingleOrDefault();
			if (button != null)
			{
				button.ToolTip = Localization.GetString("LastPageText.Grid", LocalResourceFile);
			}

			button = buttons.Where(b => b.Text == "Go").SingleOrDefault();
			if (button != null)
			{
				button.Text = Localization.GetString("GoToPageButton.Grid", LocalResourceFile);
				button.ToolTip = Localization.GetString("GoToPageButtonToolTip.Grid", LocalResourceFile);
			}

			button = buttons.Where(b => b.Text == "Change").SingleOrDefault();
			if (button != null)
			{
				button.Text = Localization.GetString("ChangePageSizeButton.Grid", LocalResourceFile);
				button.ToolTip = Localization.GetString("ChangePageSizeButtonToolTip.Grid", LocalResourceFile);
			}

		}

		protected void dgFormReport_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			TableCell oTableCell = default(TableCell);
			string strCommandName = default(string);
			Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = default(Code5Systems.FormMaster.Business.FormDataController);
			
			strCommandName = ((LinkButton) e.CommandSource).CommandName;
			
			switch (strCommandName)
			{
				case "Edit":
					oTableCell = e.Item.Cells[2];
					
					if (oTableCell != null)
					{
						_intFormDataId = System.Convert.ToInt32(oTableCell.Text);
						ViewState.Add("FormDataID", _intFormDataId.ToString());
						this.pnlForm.Visible = true;
						this.pnlReport.Visible = false;
						BindFormData();
						if (this.formWizard.WizardSteps.Count > 0)
						{
							this.formWizard.ActiveStepIndex = 0;
						}
					}
					break;
					
				case "Delete":
					oTableCell = e.Item.Cells[2];
					if (oTableCell != null)
					{
						objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
						_intFormDataId = System.Convert.ToInt32(oTableCell.Text);
						objFormDataCtl.Delete(ModuleId, _intFormDataId, _objFormInfo);
						BindGrid();
					}
					break;
					
			}
		}

		protected void dgFormReport_EditCommand(object source, GridCommandEventArgs e)
		{
			TableCell oTableCell = default(TableCell);

			oTableCell = e.Item.Cells[4];

			if (oTableCell != null)
			{
				_intFormDataId = System.Convert.ToInt32(oTableCell.Text);
				ViewState.Add("FormDataID", _intFormDataId.ToString());
				this.pnlForm.Visible = true;
				this.pnlReport.Visible = false;
				e.Canceled = true;
				BindGrid();
				BindFormData();
				if (this.formWizard.WizardSteps.Count > 0)
				{
					this.formWizard.ActiveStepIndex = 0;
				}
			}
		}

		protected void dgFormReport_DeleteCommand(object source, GridCommandEventArgs e)
		{
			TableCell oTableCell = default(TableCell);
			Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = default(Code5Systems.FormMaster.Business.FormDataController);

			oTableCell = e.Item.Cells[4];
			if (oTableCell != null)
			{
				objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
				_intFormDataId = System.Convert.ToInt32(oTableCell.Text);
				objFormDataCtl.Delete(ModuleId, _intFormDataId, _objFormInfo);
				BindGrid();
			}
		}

		protected void dgFormReport_SortCommand(object source, GridSortCommandEventArgs e)
		{
			//GridSortExpression sortExpr = new GridSortExpression();
			//if (e.NewSortOrder == GridSortOrder.None)
			//{
			//	if (e.OldSortOrder == GridSortOrder.Ascending)
			//		sortExpr.SortOrder = GridSortOrder.Descending;
			//	else
			//		sortExpr.SortOrder = GridSortOrder.Ascending;
			//}
			//else
			//{
			//	sortExpr.SortOrder = e.NewSortOrder;
			//}
			//sortExpr.FieldName = e.SortExpression;
			//this.dgFormReport.MasterTableView.SortExpressions.Clear();
			//this.dgFormReport.MasterTableView.SortExpressions.AddSortExpression(sortExpr);
			////BindGrid(e.NewSortOrder);

			if (!e.Item.OwnerTableView.SortExpressions.ContainsExpression(e.SortExpression))
			{
				GridSortExpression sortExpr = new GridSortExpression();
				sortExpr.FieldName = e.SortExpression;
				sortExpr.SortOrder = GridSortOrder.Ascending;
				e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
			}
		}

		protected void dgFormReport_PageIndexChanged(object source, GridPageChangedEventArgs e)
		{
			this.dgFormReport.CurrentPageIndex = e.NewPageIndex;
		}

		protected void dgFormReport_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
		{
			if (e.RebindReason != GridRebindReason.InitialLoad)
			{
				Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();

				DateTime dtEnd = default(DateTime);
				dtEnd = this.txtEndDate.SelectedDate.Value;
				dtEnd = System.Convert.ToDateTime(dtEnd.Date.AddDays(1).AddSeconds(-1));
				DataSet ds = objFormDataCtl.List(ModuleId, this.txtStartDate.SelectedDate.Value, dtEnd, this.dgFormReport.CurrentPageIndex + 1, this.dgFormReport.PageSize, this.ControlPath);
				if (ds.Tables.Count == 2)
				{
					this.dgFormReport.DataSource = ds.Tables[0];
					this.dgFormReport.VirtualItemCount = System.Convert.ToInt32(ds.Tables["Records"].Rows[0]["RecordCount"]);
					SetReportButtons(true);
				}
				else
				{
					this.dgFormReport.DataSource = new DataTable();
					this.dgFormReport.VirtualItemCount = 0;
					SetReportButtons(false);
				}
				
			}
			else
			{
				this.dgFormReport.DataSource = new DataTable();
			}
		}

		protected void cmdSubmit_Click(System.Object sender, System.EventArgs e)
		{
			Page.Validate();
			if (Page.IsValid)
			{
				try
				{
					Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
					XDocument objUpdateResultsXmlDoc;
					
					Code5Systems.FormMaster.Business.FormDataInfo objFormDataInfo = objFormDataCtl.Get(_intFormDataId, ModuleId);
					
					objUpdateResultsXmlDoc = objFormDataCtl.GetFormResults(ModuleId, this.pnlForm, this.ControlPath, _disabledValidators, PortalId, this.UserId, _intFormDataId);
					
					ViewState.Remove("FormDataID");
					
					this.pnlForm.Visible = false;
					this.pnlReport.Visible = true;
					BindGrid();
				}
				catch (IOException exIO)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, exIO.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				catch (SqlException exSql)
				{
					DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, exSql.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				catch (Exception exc)
				{
					Exceptions.ProcessModuleLoadException(this.LoaderCtl, exc);
				}
			}
		}

		protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			ViewState.Remove("FormDataID");
			this.pnlForm.Visible = false;
			this.pnlReport.Visible = true;
			BindGrid();
		}
		
		protected void formReportWizard_ActiveStepChanged(object sender, System.EventArgs e)
		{
			string defaultButtonId;
			_objFormCtl.FormInfo.CurrentPage = _objFormCtl.Pages[this.formWizard.ActiveStepIndex];
			this.formWizard.HeaderText = string.Empty;
			if (_objFormCtl.FormInfo.CurrentPage.UseTitle)
			{
				this.formWizard.HeaderText = _objFormCtl.FormInfo.CurrentPage.Title;
			}
			
			defaultButtonId = string.Empty;
			_validationGroup = string.Empty;
			
			foreach (BaseValidator val in Utility.GetChildsRecursive(this.formWizard.ActiveStep).OfType<BaseValidator>())
			{
				_validationGroup = val.ValidationGroup;
				break;
			}
			
			// Add ValidationGroup to any Buttons
			foreach (Button btn in Utility.GetChildsRecursive(this.formWizard).OfType<Button>())
			{
				if (btn.CausesValidation && (btn.CommandName == "MoveNext" || btn.CommandName == "MoveComplete"))
				{
					btn.ValidationGroup = _validationGroup;
				}
				
				if (!(btn.CommandName == "MoveNext" || btn.CommandName == "MoveComplete"))
				{
					btn.UseSubmitBehavior = false;
				}
			}
			
			// Add ValidationGroup to any LinkButtons
			foreach (LinkButton btn in Utility.GetChildsRecursive(this.formWizard).OfType<LinkButton>())
			{
				if (btn.CausesValidation && (btn.CommandName == "MoveNext" || btn.CommandName == "MoveComplete"))
				{
					btn.ValidationGroup = _validationGroup;
				}
			}
			
			// Add ValidationGroup to any ImageButtons
			foreach (ImageButton btn in Utility.GetChildsRecursive(this.formWizard).OfType<ImageButton>())
			{
				if (btn.CausesValidation && (btn.CommandName == "MoveNext" || btn.CommandName == "MoveComplete"))
				{
					btn.ValidationGroup = _validationGroup;
				}
			}
			
		}
		
		protected void formWizard_FinishButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
		{
			cmdSubmit_Click(sender, null);
		}
		
		protected void formWizard_NextButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
		{
			foreach (BaseValidator val in Utility.GetChildsRecursive(this.formWizard.ActiveStep).OfType<BaseValidator>())
			{
				_validationGroup = val.ValidationGroup;
				break;
			}
			if (e.NextStepIndex > e.CurrentStepIndex)
			{
				Page.Validate(_validationGroup);
				if (!Page.IsValid)
				{
					e.Cancel = true;
				}
			}
		}
			
		protected void LoadSideBar(object sender, EventArgs e)
		{
			DataList dList = (DataList) sender;
			dList.RepeatDirection = RepeatDirection.Horizontal;
			dList.RepeatLayout = RepeatLayout.Flow;
			dList.Attributes.Add("style", "display:none;");
			dList.Attributes.Add("class", "fmwizardsteps");
		}
		
#endregion
			
#region Data Bind Methods
		
		//Retrive the data based on the given start and end dates
		private void BindGrid()
		{
			DataSet ds = null;
			try
			{
				this.dgFormReport.EditIndexes.Clear();
				this.dgFormReport.DataSource = null;
				Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();

				if (_fdid > 0)
				{
					Code5Systems.FormMaster.Business.FormDataInfo objFormDataInfo = objFormDataCtl.Get(_fdid, ModuleId);
					if (_objFormInfo.UseExtTable)
					{
						ds = objFormDataCtl.GetExternalData(_objFormInfo, objFormDataInfo);
					}
					else
					{
						string strResults = "<Report><Post><FormDataID>" + _fdid.ToString() + "</FormDataID><FormData>";
						strResults += objFormDataInfo.FormData;
						strResults += "</FormData></Post></Report>";
						ds = objFormDataCtl.GetDataSetFromFormResults(strResults, this.ControlPath);
					}
				}
				else
				{
					DateTime dtEnd = default(DateTime);
					dtEnd = this.txtEndDate.SelectedDate.Value;
					dtEnd = System.Convert.ToDateTime(dtEnd.Date.AddDays(1).AddSeconds(-1));
					ds = objFormDataCtl.List(ModuleId, this.txtStartDate.SelectedDate.Value, dtEnd, this.dgFormReport.CurrentPageIndex + 1, this.dgFormReport.PageSize, this.ControlPath);
				}
				this.dgFormReport.AutoGenerateColumns = true;
				
				if (ds.Tables.Count  > 0)
				{
					this.dgFormReport.DataSource = ds.Tables[0];
					if (ds.Tables.Count == 2 && _fdid == 0)
					{
						this.dgFormReport.VirtualItemCount = System.Convert.ToInt32(ds.Tables["Records"].Rows[0]["RecordCount"]);
					}
					else
					{
						this.dgFormReport.VirtualItemCount = 1;
					}
					SetReportButtons(true);
				}
				else
				{
					this.dgFormReport.DataSource = new DataTable();
					this.dgFormReport.VirtualItemCount = 0;
					SetReportButtons(false);
				}

				this.dgFormReport.DataBind();

				if (this._objFormSettings.HidePostedBy)
				{
					try
					{
						var submittedByCol = this.dgFormReport.MasterTableView.GetColumn(Localization.GetString("SubmittedBy", Utility.GetSharedResourceFile()));
						if (submittedByCol != null)
						{
							submittedByCol.Visible = false;
						}
					}
					catch { }
				}
				
				LocalizeGrid();
			}
			catch (ArgumentException argEx)
			{
				string strMsg = Localization.GetString(argEx.Message, this.LocalResourceFile);
				if (strMsg == null)
				{
					strMsg = argEx.Message;
				}
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, strMsg, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
			catch (System.Data.SqlClient.SqlException sqlEx)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, sqlEx.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this.LoaderCtl, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				Exceptions.ProcessModuleLoadException(LoaderCtl, exc);
			}
			
		}
	
		private void BindFormData()
		{
			WebControl oWebControl = null;
			HtmlControl oHtmlControl = null;
			HtmlInputHidden oHiddenField = null;
			TextEditor oTextEditor = null;
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			Code5Systems.FormMaster.Business.FormDataInfo objFormDataInfo = default(Code5Systems.FormMaster.Business.FormDataInfo);
			Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			string strQuestion = string.Empty;
			string strAnswer = default(string);
			string strEmailSendToControl = string.Empty;
			ListItem oListItem = default(ListItem);
			string strResults = default(string);
			DataSet ds = default(DataSet);
			Code5Systems.FormMaster.Business.FormMappingController objFormMapCtl = default(Code5Systems.FormMaster.Business.FormMappingController);
			List<Code5Systems.FormMaster.Business.FormMappingInfo> alMappings = default(List<Code5Systems.FormMaster.Business.FormMappingInfo>);
			Dictionary<string, string> oMapDict = new Dictionary<string, string>();
			List<Code5Systems.FormMaster.Business.FormControlInfo> controlsArray = default(List<Code5Systems.FormMaster.Business.FormControlInfo>);
			XDocument xDoc = default(XDocument);
			
			objFormDataInfo = objFormDataCtl.Get(_intFormDataId, ModuleId);
			
			if (_objFormInfo.UseExtTable)
			{
				ds = objFormDataCtl.GetExternalData(_objFormInfo, objFormDataInfo);
				objFormMapCtl = new Code5Systems.FormMaster.Business.FormMappingController();
				alMappings = objFormMapCtl.GetByForm(this._objFormCtl.FormInfo.FormID);
				System.Collections.IEnumerator mapEnumerator = alMappings.GetEnumerator();
				Code5Systems.FormMaster.Business.FormMappingInfo oMapping = default(Code5Systems.FormMaster.Business.FormMappingInfo);
				while (mapEnumerator.MoveNext())
				{
					oMapping = (Code5Systems.FormMaster.Business.FormMappingInfo) mapEnumerator.Current;
					oMapDict.Add(oMapping.FormField, oMapping.TableField);
				}
			}
			else
			{
				strResults = "<Report><Post><FormDataID>" + _intFormDataId.ToString() + "</FormDataID><FormData>";
				strResults += objFormDataInfo.FormData;
				strResults += "</FormData></Post></Report>";
				ds = objFormDataCtl.GetDataSetFromFormResults(strResults, this.ControlPath);
			}
			
			DataTable dtPostdata = ds.Tables[0];
			
			string strSubmittedBy = "";
			if (!(dtPostdata.Columns["Submitted_By"] == null))
			{
				strSubmittedBy = System.Convert.ToString(dtPostdata.Rows[0]["SubmittedBy"]);
			}
			
			Label lblSubmittedBy = new Label();
			
			lblSubmittedBy.ID = "lblSubmittedBy";
			lblSubmittedBy.Text = strSubmittedBy;
			lblSubmittedBy.Visible = false;
			this.phForm.Controls.Add(lblSubmittedBy);
			
			//Determine if we are using a Form Value for the Send To Email address
			if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.UseForm)
			{
				strEmailSendToControl = _objFormInfo.EmailSendToControl;
			}
			
			foreach (Code5Systems.FormMaster.Business.FormPageInfo oPage in _objFormCtl.Pages)
			{
				xDoc = XDocument.Parse(oPage.PageData);
				xDoc = objFormDataCtl.SortControls(xDoc, this.ControlPath);
				
				//Get an List(Of FormControlInfo) for this form
				controlsArray = _objFormCtl.GetFormControlArray(xDoc);
				
				foreach (Code5Systems.FormMaster.Business.FormControlInfo tempLoopVar_oFormControlInfo in controlsArray)
				{
					oFormControlInfo = tempLoopVar_oFormControlInfo;
					if (_objFormInfo.UseExtTable)
					{
						if (oMapDict.ContainsKey(oFormControlInfo.ID))
						{
							strQuestion = oMapDict[oFormControlInfo.ID];
						}
					}
					else
					{
						strQuestion = Utility.GetValidControlID(oFormControlInfo.FieldName);
						strQuestion = (string) (strQuestion.Replace("_", " ").Trim());
					}
					
					if (oFormControlInfo.Type != Code5Systems.FormMaster.Business.ControlType.FileUpload)
					{
						if (!(dtPostdata.Columns[strQuestion] == null))
						{
							if (dtPostdata.Columns[strQuestion].DataType == typeof(System.Guid))
							{
								strAnswer = (string) (((Guid) (dtPostdata.Rows[0][strQuestion])).ToString());
							}
							else if (dtPostdata.Rows[0][strQuestion] == System.DBNull.Value)
							{
								strAnswer = string.Empty;
							}
							else
							{
								strAnswer = (dtPostdata.Rows[0][strQuestion]).ToString();
							}
							
							if (oFormControlInfo.EncryptField)
							{
								strAnswer = Utility.EncryptString(strAnswer);
							}
							
							switch (oFormControlInfo.Type)
							{
								case Code5Systems.FormMaster.Business.ControlType.FileUpload:
									oHtmlControl = Utility.GetChildsRecursive(pnlForm).OfType<HtmlControl>().Where(c => c.ID == oFormControlInfo.ID).SingleOrDefault();
									break;
								case Code5Systems.FormMaster.Business.ControlType.HiddenField:
									if (oFormControlInfo.FieldName.ToLower() == "datarecordid")
									{
										oHiddenField = Utility.GetChildsRecursive(pnlForm).OfType<HtmlInputHidden>().Where(c => c.ID == "DataRecordID").SingleOrDefault();
									}
									else
									{
										oHiddenField = Utility.GetChildsRecursive(pnlForm).OfType<HtmlInputHidden>().Where(c => c.ID == oFormControlInfo.ID).SingleOrDefault();
									}
									break;
									
								case Code5Systems.FormMaster.Business.ControlType.HTMLEditor:
									oTextEditor = Utility.GetChildsRecursive(pnlForm).OfType<TextEditor>().Where(c => c.ID == oFormControlInfo.ID).SingleOrDefault();
									break;
								default:
									oWebControl = Utility.GetChildsRecursive(pnlForm).OfType<WebControl>().Where(c => c.ID == oFormControlInfo.ID).SingleOrDefault();
									break;
							}
							
							if ((oWebControl != null) || (oTextEditor != null))
							{
								switch (oFormControlInfo.Type)
								{
									case Code5Systems.FormMaster.Business.ControlType.CheckBox:
										CheckBox oCheckBox = default(CheckBox);
									
										oCheckBox = (CheckBox) oWebControl;
										if (oCheckBox != null)
										{
										
											oCheckBox.Checked = false;
										
											if (strAnswer == Localization.GetString("Yes", Utility.GetSharedResourceFile()) || strAnswer == Localization.GetString("True", Utility.GetSharedResourceFile()) || strAnswer == "TG")
											{
												((CheckBox) oWebControl).Checked = true;
											}
											else
											{
												bool isChecked = default(bool);
												bool.TryParse(strAnswer, out isChecked);
												oCheckBox.Checked = isChecked;
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.TextBox:
										if (oFormControlInfo.UseCalendar)
										{
											DateTime dt;
											if (DateTime.TryParse(strAnswer, out dt))
											{
												RadDatePicker datePicker = oWebControl as RadDatePicker;
												datePicker.SelectedDate = dt;
											}
										}
										else
										{
											TextBox oTextBox = default(TextBox);
											oTextBox = (TextBox)oWebControl;
											if (oTextBox != null)
											{
												oTextBox.Text = strAnswer;
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.RadioButtonList:
										RadioButtonList oRadioButtonList = default(RadioButtonList);
									
										oRadioButtonList = (RadioButtonList) oWebControl;
									
										if (oRadioButtonList != null)
										{
											//Clear any selected ListItem
											oRadioButtonList.SelectedIndex = -1;
											if (oFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text)
											{
												oListItem = oRadioButtonList.Items.FindByText(strAnswer);
											}
											else
											{
												oListItem = oRadioButtonList.Items.FindByValue(strAnswer);
											}
										
											if (oListItem != null)
											{
												oListItem.Selected = true;
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.DropDownList:
										DropDownList oDropDownList = (DropDownList) oWebControl;
									
										if (oDropDownList != null)
										{
											//Clear any selected item
											oDropDownList.SelectedIndex = -1;
											if (oFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text)
											{
												oListItem = ((DropDownList) oWebControl).Items.FindByText(strAnswer);
											}
											else
											{
												oListItem = ((DropDownList) oWebControl).Items.FindByValue(strAnswer);
											}
										
										
											if (oListItem != null)
											{
												oListItem.Selected = true;
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.CheckBoxList:
										CheckBoxList oCheckBoxList = (CheckBoxList) oWebControl;
									
										//Clear Any Selected Items
										if (oCheckBoxList != null)
										{
											foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
											{
												oListItem = tempLoopVar_oListItem;
												oListItem.Selected = false;
											}
										
											foreach (string s in strAnswer.Split(','))
											{
												if (oFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text)
												{
													oListItem = oCheckBoxList.Items.FindByText(s);
												}
												else
												{
													oListItem = oCheckBoxList.Items.FindByValue(s);
												}
											
												if (oListItem != null)
												{
													oListItem.Selected = true;
												}
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.ListBox:
										ListBox oListBox = (ListBox) oWebControl;
									
										if (oListBox != null)
										{
											//Clear Any Selected Items
											foreach (ListItem tempLoopVar_oListItem in oListBox.Items)
											{
												oListItem = tempLoopVar_oListItem;
												oListItem.Selected = false;
											}
										
											foreach (string s in strAnswer.Split(','))
											{
												if (oFormControlInfo.ListItemToSave == Code5Systems.FormMaster.Business.FormController.ListItemToSave.Text)
												{
													oListItem = oListBox.Items.FindByText(s);
												}
												else
												{
													oListItem = oListBox.Items.FindByValue(s);
												}
											
												if (oListItem != null)
												{
													oListItem.Selected = true;
												}
											}
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.Label:
										Label oLabel = (Label) oWebControl;
									
										if (oLabel != null)
										{
											oLabel.Text = oFormControlInfo.Text;
										}
										break;
									case Code5Systems.FormMaster.Business.ControlType.HiddenField:
										oHiddenField.Value = strAnswer;
										break;
									case Code5Systems.FormMaster.Business.ControlType.HTMLEditor:
										oTextEditor.Text = strAnswer;
										break;
							}
						}
					}
				}
			}
		}
	}

		private void LocalizeGrid()
		{
			this.dgFormReport.SortingSettings.SortToolTip = Localization.GetString("ClickToSort.Grid", LocalResourceFile);
			this.dgFormReport.SortingSettings.SortedAscToolTip = Localization.GetString("SortedAscToolTip.Grid", LocalResourceFile);
			this.dgFormReport.SortingSettings.SortedDescToolTip = Localization.GetString("SortedDescToolTip.Grid", LocalResourceFile);
			this.dgFormReport.StatusBarSettings.LoadingText = Localization.GetString("LoadingText.Grid", LocalResourceFile);
			this.dgFormReport.StatusBarSettings.ReadyText = Localization.GetString("ReadyText.Grid", LocalResourceFile);
			this.dgFormReport.MasterTableView.NoMasterRecordsText = Localization.GetString("NoMasterRecordsText.Grid", LocalResourceFile);
		}

		private void SetReportButtons(bool enabled)
		{
			this.cmdDelete.Enabled = enabled;
			this.cmdExcel.Enabled = enabled;
			this.cmdExcel2007.Enabled = enabled;
			this.cmdWord.Enabled = enabled;
			this.cmdPDF.Enabled = enabled;
			this.cmdCsv.Enabled = enabled;
			this.cmdTab.Enabled = enabled;

			if (enabled)
			{
				this.cmdDelete.Attributes.Add("onclick", "javascript:return confirm(\'" + Localization.GetString("DeleteDataMessage", LocalResourceFile) + "\');");
			}
			else
			{
				this.cmdDelete.Attributes.Remove("onclick");
			}
		}

		private string GetExportFileName()
		{
			var tzInfo = this.UserInfo.Profile.PreferredTimeZone;
			
			DateTime dtNow = DateTime.UtcNow.Add(tzInfo.BaseUtcOffset);
			if (tzInfo.IsDaylightSavingTime(dtNow))
			{
				dtNow = dtNow.AddHours(1);
			}

			string name = String.Format("{0}-{1:D4}-{2:D2}-{3:D2}-{4:D2}{5:D2}{6:D2}", 
				this._objFormInfo.FormName.Replace(" ", "-"), 
				dtNow.Year, 
				dtNow.Month, 
				dtNow.Day,
				dtNow.Hour,
				dtNow.Minute,
				dtNow.Second);
			return name;
		}
	
#endregion
	
#region Helper Methods
	
	//Get the Download URL based on the user selected format
	private string GetDownloadUrl(string type)
	{
		CultureInfo userCulture = Utility.GetUserCulture();
		string strUrl = default(string);
		strUrl = this.ControlPath + "download.aspx?mid=" + ModuleId + "&portid=" + PortalId + "&tabid=" + TabId;
		strUrl += "&type=" + type;
		strUrl += "&sdate=" + Server.UrlEncode(this.txtStartDate.SelectedDate.Value.ToString("d", userCulture));
		strUrl += "&edate=" + Server.UrlEncode(this.txtEndDate.SelectedDate.Value.ToString("d", userCulture));
		
		return strUrl;
		
	}
	
#endregion
	
#region Properties
	public PortalModuleBase LoaderCtl
	{
		get
		{
			if (_loaderCtl == null)
			{
				_loaderCtl = this;
			}
			
			return _loaderCtl;
		}
		set
		{
			_loaderCtl = value;
		}
	}
	
	protected string StepCssClass
	{
		get
		{
			return _objFormSettings.WizardStepClass;
		}
	}
#endregion

	

	

	
	

	

	


	

}

}


